class AreaDistribution {
    constructor() {
        this.heatmapChart = null;
        this.comparisonChart = null;
        
        // 等待 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        this.initializeCharts();
        this.initializeEventListeners();
        this.updateData();
        this.startRealTimeUpdate();
    }

    initializeCharts() {
        // 初始化热力图
        const heatmapCtx = document.getElementById('moistureHeatmap');
        if (heatmapCtx) {
            this.heatmapChart = new Chart(heatmapCtx.getContext('2d'), {
                type: 'scatter',
                data: {
                    datasets: [{
                        label: '墒情分布',
                        data: this.generateHeatmapData(),
                        backgroundColor: (context) => {
                            const value = context.raw.v;
                            return this.getHeatmapColor(value);
                        },
                        pointRadius: 15,
                        pointHoverRadius: 20
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            min: 0,
                            max: 100,
                            title: {
                                display: true,
                                text: 'X轴 (m)'
                            }
                        },
                        y: {
                            min: 0,
                            max: 100,
                            title: {
                                display: true,
                                text: 'Y轴 (m)'
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: (context) => {
                                    const point = context.raw;
                                    return [
                                        `区域: ${point.area}`,
                                        `监测点: ${point.point}`,
                                        `墒情值: ${point.v}%`
                                    ];
                                }
                            }
                        }
                    }
                }
            });
        }

        // 初始化区域对比图
        const comparisonCtx = document.getElementById('areaComparisonChart');
        if (comparisonCtx) {
            this.comparisonChart = new Chart(comparisonCtx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: ['区域一', '区域二', '区域三', '区域四', '区域五'],
                    datasets: [{
                        label: '平均墒情 (%)',
                        data: this.generateMockData(5),
                        backgroundColor: 'rgba(24, 144, 255, 0.6)',
                        borderColor: 'rgba(24, 144, 255, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });
        }
    }

    initializeEventListeners() {
        // 热力图显示模式切换
        document.getElementById('heatmap-mode').addEventListener('change', (e) => {
            this.updateHeatmap(e.target.value);
        });

        // 异常点位筛选
        document.getElementById('anomaly-area-filter').addEventListener('change', () => {
            this.updateAnomalyList();
        });

        document.getElementById('anomaly-type-filter').addEventListener('change', () => {
            this.updateAnomalyList();
        });

        // 导出按钮点击事件
        document.querySelector('.export-btn').addEventListener('click', () => {
            this.exportData();
        });
    }

    generateHeatmapData() {
        const data = [];
        const areas = 5;
        const pointsPerArea = 12;

        for (let area = 1; area <= areas; area++) {
            const centerX = 20 + (area - 1) * 15;
            const centerY = 50;

            for (let point = 1; point <= pointsPerArea; point++) {
                const angle = (point - 1) * (2 * Math.PI / pointsPerArea);
                const radius = 15;
                const x = centerX + radius * Math.cos(angle);
                const y = centerY + radius * Math.sin(angle);
                const value = 20 + Math.random() * 30;

                data.push({
                    x: x,
                    y: y,
                    v: value.toFixed(1),
                    area: `区域${area}`,
                    point: `监测点${point}`
                });
            }
        }

        return data;
    }

    getHeatmapColor(value) {
        const hue = ((100 - value) * 1.2).toFixed(0);
        return `hsla(${hue}, 80%, 50%, 0.7)`;
    }

    generateMockData(count) {
        return Array.from({length: count}, () => 20 + Math.random() * 30);
    }

    updateData() {
        // 更新异常点位数量
        const abnormalCount = Math.floor(Math.random() * 10);
        document.getElementById('abnormal-points').textContent = abnormalCount;

        // 更新热力图
        this.updateHeatmap(document.getElementById('heatmap-mode').value);

        // 更新区域对比图
        this.updateComparisonChart();

        // 更新区域统计信息
        this.updateAreaStats();

        // 更新异常点位列表
        this.updateAnomalyList();
    }

    updateHeatmap(mode) {
        const data = this.generateHeatmapData();
        
        if (mode === 'temperature') {
            data.forEach(point => {
                point.v = (15 + Math.random() * 15).toFixed(1);
            });
        } else if (mode === 'anomaly') {
            data.forEach(point => {
                point.v = Math.random() > 0.8 ? (40 + Math.random() * 20).toFixed(1) : 
                         Math.random() > 0.6 ? (10 + Math.random() * 10).toFixed(1) :
                         (20 + Math.random() * 20).toFixed(1);
            });
        }

        this.heatmapChart.data.datasets[0].data = data;
        this.heatmapChart.update();
    }

    updateComparisonChart() {
        const data = this.generateMockData(5);
        this.comparisonChart.data.datasets[0].data = data;
        this.comparisonChart.update();
    }

    updateAreaStats() {
        const statsContainer = document.querySelector('.area-stats-grid');
        const areas = 5;
        let html = '';

        for (let i = 1; i <= areas; i++) {
            const avgMoisture = (20 + Math.random() * 30).toFixed(1);
            const avgTemp = (15 + Math.random() * 15).toFixed(1);
            const abnormalCount = Math.floor(Math.random() * 3);

            html += `
                <div class="area-stat-card">
                    <div class="area-stat-header">
                        <span class="area-stat-title">区域${i}</span>
                        <span class="status-tag ${this.getStatusClass(avgMoisture)}">
                            ${this.getStatusText(avgMoisture)}
                        </span>
                    </div>
                    <div class="area-stat-value">
                        ${avgMoisture}%
                    </div>
                    <div class="area-stat-footer">
                        <span>平均温度: ${avgTemp}°C</span>
                        <span>异常点位: ${abnormalCount}个</span>
                    </div>
                </div>
            `;
        }

        statsContainer.innerHTML = html;
    }

    updateAnomalyList() {
        const tbody = document.getElementById('anomaly-points-body');
        const areaFilter = document.getElementById('anomaly-area-filter').value;
        const typeFilter = document.getElementById('anomaly-type-filter').value;
        
        const mockData = this.generateMockAnomalyData(areaFilter, typeFilter);
        
        tbody.innerHTML = mockData.map(record => `
            <tr>
                <td>${record.area}</td>
                <td>${record.point}</td>
                <td>${record.moisture}%</td>
                <td>${record.temperature}°C</td>
                <td>
                    <span class="status-tag ${record.type === '墒情偏高' ? 'warning' : 'danger'}">
                        ${record.type}
                    </span>
                </td>
                <td>${record.duration}</td>
                <td>
                    <span class="status-tag ${record.status.class}">
                        ${record.status.text}
                    </span>
                </td>
                <td>
                    <button class="action-btn" onclick="alert('查看详情功能即将上线')">
                        <i class="fas fa-eye"></i>
                    </button>
                </td>
            </tr>
        `).join('');
    }

    generateMockAnomalyData(areaFilter, typeFilter) {
        const records = [];
        const count = Math.floor(Math.random() * 5) + 3;
        
        for (let i = 0; i < count; i++) {
            const area = areaFilter === 'all' ? 
                        `区域${Math.ceil(Math.random() * 5)}` : 
                        areaFilter.replace('area', '区域');
            
            const type = typeFilter === 'all' ? 
                        (Math.random() > 0.5 ? '墒情偏高' : '墒情偏低') :
                        (typeFilter === 'high' ? '墒情偏高' : '墒情偏低');
            
            const moisture = type === '墒情偏高' ? 
                           (40 + Math.random() * 20).toFixed(1) :
                           (10 + Math.random() * 10).toFixed(1);
            
            records.push({
                area,
                point: `监测点${Math.ceil(Math.random() * 12)}`,
                moisture,
                temperature: (15 + Math.random() * 15).toFixed(1),
                type,
                duration: `${Math.ceil(Math.random() * 120)}分钟`,
                status: this.getAnomalyStatus(moisture)
            });
        }
        
        return records;
    }

    getStatusClass(value) {
        if (value < 20) return 'danger';
        if (value > 40) return 'warning';
        return 'normal';
    }

    getStatusText(value) {
        if (value < 20) return '偏干';
        if (value > 40) return '偏湿';
        return '适宜';
    }

    getAnomalyStatus(value) {
        if (value < 20) {
            return { text: '需处理', class: 'danger' };
        } else if (value > 40) {
            return { text: '需关注', class: 'warning' };
        }
        return { text: '监测中', class: 'normal' };
    }

    startRealTimeUpdate() {
        // 每30秒更新一次数据
        setInterval(() => {
            this.updateData();
        }, 30000);
    }

    exportData() {
        // 模拟导出功能
        alert('数据导出功能即将上线');
    }
}

// 创建实例
window.areaDistribution = new AreaDistribution(); 